package com.hfi.observer.demo01;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/6/29.
 */
class StockObserver {
    private String name;
    private Secretary sec;

    public StockObserver(String name, Secretary sec) {
        this.name = name;
        this.sec = sec;
    }

    // 观察者要获得前台类的action
    public void update(){
        System.out.println(sec.getAction() +" " + name + "关闭股票行情，继续工作 ");
    }
}


class Secretary {
    // 观察者列表
    private List<StockObserver> observers = new ArrayList<>();
    // 要观察的状态
    private String action;

    public String getAction() {
        return action;
    }

    public void setAction(String action) {
        this.action = action;
    }

    // 注册观察者
    public void attach(StockObserver observer) {
        observers.add(observer);
    }

    // 移除观察者
    public void detach(StockObserver observer) {
        observers.remove(observer);
    }

    // 通知
    public void notifier() {
        for (StockObserver o : observers
                ) {
            o.update();
        }
    }

}

public class Test {

    public static void main(String[] args) {
        Secretary tongzizhe = new Secretary();
        StockObserver tongshi1 = new StockObserver("魏关姹", tongzizhe);
        StockObserver tongshi2 = new StockObserver("易管查", tongzizhe);

        // 注册两位同事
        tongzizhe.attach(tongshi1);
        tongzizhe.attach(tongshi2);

        // 发现老板回来
        tongzizhe.setAction("老板回来了！");

        // 通知两个同事
        tongzizhe.notifier();
    }
}
